package com.example.exam.servlet;

import com.example.exam.dao.StudentDAO;
import com.example.exam.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录Servlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private StudentDAO studentDAO = new StudentDAO();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置响应编码
        response.setContentType("text/html; charset=UTF-8");
        // 转发到登录页面
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        
        // 获取表单参数
        String studentId = request.getParameter("studentId");
        String password = request.getParameter("password");
        
        // 验证登录
        if (studentDAO.validateLogin(studentId, password)) {
            // 登录成功，获取学生信息
            Student student = studentDAO.getStudentById(studentId);
            
            // 将学生信息存入session
            HttpSession session = request.getSession();
            session.setAttribute("student", student);
            
            // 重定向到首页
            response.sendRedirect(request.getContextPath() + "/dashboard");
        } else {
            // 登录失败，返回错误信息
            request.setAttribute("error", "学号或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}